package com.itheima.tlias84.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.entity.Log;
import com.itheima.tlias84.mapper.DataStatisticsMapper;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.po.LoginParam;
import com.itheima.tlias84.po.PageParam;
import com.itheima.tlias84.service.LoginService;
import com.itheima.tlias84.utils.JwtUtil;
import com.itheima.tlias84.utils.ResultUtil;
import com.itheima.tlias84.vo.PageVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    EmpMapper empMapper;
    @Resource
    DataStatisticsMapper dataStatisticsMapper;
    @Override
    public ResultUtil login(LoginParam param) {

        Emp emp = empMapper.selectEmpByUsername(param.getUsername());
        if (Objects.isNull(emp) || !emp.getPassword().equals(param.getPassword())){
            return ResultUtil.fail("用户名或密码不正确");
        }
        String token = JwtUtil.generateToken(emp.getUsername(), emp.getPassword(), 30);
        JSONObject result = new JSONObject();
        result.put("id",emp.getId());
        result.put("username",emp.getUsername());
        result.put("name",emp.getName());
        result.put("token",token);
        return ResultUtil.success(result);
    }

    @Override
    public ResultUtil selectLog(PageParam param) {
        Page<Object> page = PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Log> logs = dataStatisticsMapper.selectLog(param);
        PageVO<Log> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(logs);
        return ResultUtil.success(pageVO);
    }

    @Override
    public int insertLog(Log log) {
        return dataStatisticsMapper.insertLog(log);
    }


}
